/*
 * ===========================================================================
 *       Filename:  gpio.c
 *    Description:  Write or Read gpio value.
 * ===========================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "include/gpio.h"

#define  GPIO_DEV	"/dev/gpio"

int gpio_fd =-1;
unsigned int gpio_port[12] = { 100, 101, 102, 97, 98, 99, 
			103, 104, 105, 106, 107, 108 };
int array[2];

void open_gpio()
{
	int i;
	memset(array,0,2);

	gpio_fd = open(GPIO_DEV, O_RDWR);
	if( -1 == gpio_fd ) {
		printf("Error: fail to open GPIO device: %s\n", GPIO_DEV);
		exit(2);
	}
}

void close_gpio()
{
	close(gpio_fd);
}

void set_input(int gpio)
{
	/* Set gpio port to 1. */
	array[0] = gpio_port[gpio];
	ioctl(gpio_fd, IN_FLAG  , array);
}

void set_output(int gpio)
{
	/* Set gpio port to 1. */
	array[0] = gpio_port[gpio];
	ioctl(gpio_fd, OUT_FLAG  , array);
}

/**************************************
 * gpio port number from 0 to 11
 *************************************/
void SET(int gpio)
{
	/* Set gpio port to 1. */
	array[0] = gpio_port[gpio];
	array[1] = 1;
	ioctl(gpio_fd, WRITE_FLAG, array);
}

void CLR(int gpio)
{
	/* Clear gpio port to 0. */
	array[0] = gpio_port[gpio];
	array[1] = 0;
	ioctl(gpio_fd, WRITE_FLAG, array);
}

int RDP(int gpio)
{
	/* Read gpio port value.
	 * Return value: 0 or 1.
	 */
	array[0] = gpio_port[gpio];
	ioctl(gpio_fd, READ_FLAG, array);
	return( array[1] );
}

int main()
{
	//volatile int a,b;
	int i;
	open_gpio();
	set_output(8);
	while(1) {
		SET(8);
		for(i=500;i>0;i--) {
			;
		} //delay
		CLR(8);
		for(i=4000;i>0;i--) {
			;
		} //delay
	}
}
